import unittest
from common.base import By
from common.functions import browser_operation
from page.reception.login_page import LoginPage
from page.reception.shopcart_page import ShopCartPage
from page.reception.index_page import IndexPage


class ShopCartTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        # 打开浏览器
        driver = browser_operation()
        driver.implicitly_wait(5)

        # 创建LoginPage,ShopCartPage和IndexPage对象
        cls.login = LoginPage(driver)
        cls.shopcart = ShopCartPage(driver)
        cls.index = IndexPage(driver)
        driver.implicitly_wait(5)

        # 请求目标网址,点击登录
        cls.login.get_website('http://172.16.140.55/ecshop/')
        cls.login.click((By.XPATH, '//*[@id="ECS_MEMBERZONE"]/a[1]'))

        # 登录操作
        cls.login.input_username('Nicole')
        cls.login.input_password('wy990810')
        cls.login.btn_login()

    def tearDown(self) -> None:
        self.index.home_btn()
        self.index.shopcart_btn()

    def test01_shopcart(self):
        # 添加商品到购物车
        self.shopcart.add_shopcart()

        # 断言跳转到购物车后里面的商品是添加的商品
        goods_name = self.shopcart.get_element_text((By.XPATH, '//*[@id="formCart"]/table[1]/tbody/tr[2]/td[1]/a[2]'))
        self.assertEqual('视频', goods_name)

    def test02_shopcart(self):
        # 点击继续购物返回主页
        self.shopcart.continue_shop()

        # 断言点击继续购物后是跳转到首页
        title = self.shopcart.get_title()
        self.assertEqual('ECSHOP演示站 - Powered by ECShop', title)

    def test03_shopcart(self):
        # 查看购物车
        self.shopcart.check_shopcart()

        # 断言购物车内的商品名和点击添加购物车时的相同
        goods_name = self.shopcart.get_element_text((By.XPATH, '//*[@id="formCart"]/table[1]/tbody/tr[2]/td[1]/a[2]'))
        self.assertEqual('视频', goods_name)

    def test04_shopcart(self):
        # 修改购物车商品数量
        self.shopcart.modify_shopcart()

        # 断言修改购物车内商品的购买数量点击刷新购物车后，右上角查看购物车里的数字也会随着改变
        goods_number = self.shopcart.get_element_text((By.XPATH, '//*[@id="ECS_CARTINFO"]/a'))
        self.assertEqual('购物车(3)', goods_number)

    def test05_shopcart(self):
        # 删除购物车
        self.shopcart.delete_goods()

        # 断言删除购物车商品后，商品在购物车页面不存在
        goods = self.shopcart.get_element_text((By.XPATH, '//*[@id="formCart"]/table[1]/tbody/tr[2]/td[1]/a[2]'))
        self.assertIsNone(goods)

    def test06_shopcart(self):
        # 点击继续购物返回主页
        self.shopcart.continue_shop()

        # 添加商品到购物车
        self.shopcart.add_shopcart()

        # 清空购物车
        self.shopcart.clear_shopcart()

        # 断言清空购物车后，右上角查看购物车里的数字为0
        goods_number = self.shopcart.get_element_text((By.XPATH, '//*[@id="ECS_CARTINFO"]/a'))
        self.assertEqual('购物车(0)', goods_number)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.login.quit()


if __name__ == '__main__':
    unittest.main(verbosity=2)
